package com.ruoyi.project.configureSystem.service.impl;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.aspectj.lang.annotation.DataScope;
import com.ruoyi.framework.web.domain.TreeSelect;
import com.ruoyi.framework.web.domain.server.TreeSelectArea;
import com.ruoyi.project.configureSystem.domain.SysArea;
import com.ruoyi.project.configureSystem.mapper.SysAreaMapper;
import com.ruoyi.project.configureSystem.service.ISysAreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 区域管理 服务实现
 * 
 * @author ruoyi
 */
@Service
public class SysAreaServiceImpl implements ISysAreaService
{
    @Autowired
    private SysAreaMapper areaMapper;

    /**
     * 查询区域管理数据
     * 
     * @param 
     * @return 区域信息集合
     */
    @Override
//    @DataScope(deptAlias = "d")
    public List<SysArea> selectAreaList(SysArea area)
    {
        return areaMapper.selectAreaList(area);
    }

    /**
     * 构建前端所需要树结构
     * 
     * @param 
     * @return 树结构列表
     */
    @Override
    public List<SysArea> buildAreaTree(List<SysArea> areas)
    {
        List<SysArea> returnList = new ArrayList<SysArea>();
        List<Long> tempList = new ArrayList<Long>();
        for (SysArea area : areas)
        {
            tempList.add(area.getAreaId());
        }
        for (Iterator<SysArea> iterator = areas.iterator(); iterator.hasNext();)
        {
            SysArea area = (SysArea) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(area.getParentId()))
            {
                recursionFn(areas, area);
                returnList.add(area);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = areas;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     * 
     * @param
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelectArea> buildAreaTreeSelect(List<SysArea> areas)
    {
        List<SysArea> areaTrees = buildAreaTree(areas);
        return areaTrees.stream().map(TreeSelectArea::new).collect(Collectors.toList());
    }

    /**
     * 根据角色ID查询区域树信息
     * 
     * @param roleId 角色ID
     * @return 选中区域列表
     */
    @Override
    public List<Integer> selectAreaListByRoleId(Long roleId)
    {
        return areaMapper.selectAreaListByRoleId(roleId);
    }

    /**
     * 根据区域ID查询信息
     * 
     * @param
     * @return 区域信息
     */
    @Override
    public SysArea selectAreaById(Long areaId)
    {
        return areaMapper.selectAreaById(areaId);
    }

    /**
     * 是否存在子节点
     * 
     * @param
     * @return 结果
     */
    @Override
    public boolean hasChildByAreaId(Long areaId)
    {
        int result = areaMapper.hasChildByAreaId(areaId);
        return result > 0 ? true : false;
    }

    /**
     * 查询区域是否存在用户
     * 
     * @param
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkAreaExistUser(Long areaId)
    {
        int result = areaMapper.checkAreaExistUser(areaId);
        return result > 0 ? true : false;
    }

    /**
     * 校验区域名称是否唯一
     * 
     * @param
     * @return 结果
     */
    @Override
    public String checkAreaNameUnique(SysArea area)
    {
        Long areaId = StringUtils.isNull(area.getAreaId()) ? -1L : area.getAreaId();
        SysArea info = areaMapper.checkAreaNameUnique(area.getAreaName(), area.getParentId());
        if (StringUtils.isNotNull(info) && info.getAreaId().longValue() != areaId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 新增保存区域信息
     * 
     * @param
     * @return 结果
     */
    @Override
    public int insertArea(SysArea area)
    {
        SysArea info = areaMapper.selectAreaById(area.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.AREA_NORMAL.equals(info.getStatus()))
        {
            throw new CustomException("区域停用，不允许新增");
        }
        area.setAncestors(info.getAncestors() + "," + area.getParentId());
        return areaMapper.insertArea(area);
    }

    /**
     * 修改保存区域信息
     * 
     * @param
     * @return 结果
     */
    @Override
    public int updateArea(SysArea area)
    {
        SysArea newParentArea = areaMapper.selectAreaById(area.getParentId());
        SysArea oldArea = areaMapper.selectAreaById(area.getAreaId());
        if (StringUtils.isNotNull(newParentArea) && StringUtils.isNotNull(oldArea))
        {
            String newAncestors = newParentArea.getAncestors() + "," + newParentArea.getAreaId();
            String oldAncestors = oldArea.getAncestors();
            area.setAncestors(newAncestors);
            updateAreaChildren(area.getAreaId(), newAncestors, oldAncestors);
        }
        int result = areaMapper.updateArea(area);
        if (UserConstants.AREA_NORMAL.equals(area.getStatus()))
        {
            // 如果该区域是启用状态，则启用该区域的所有上级区域
            updateParentAreaStatus(area);
        }
        return result;
    }

    /**
     * 修改该区域的父级区域状态
     * 
     * @param
     */
    private void updateParentAreaStatus(SysArea area)
    {
        String updateBy = area.getUpdateBy();
        area = areaMapper.selectAreaById(area.getAreaId());
        area.setUpdateBy(updateBy);
        areaMapper.updateAreaStatus(area);
    }

    /**
     * 修改子元素关系
     * 
     * @param
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateAreaChildren(Long areaId, String newAncestors, String oldAncestors)
    {
        List<SysArea> children = areaMapper.selectChildrenAreaById(areaId);
        for (SysArea child : children)
        {
            child.setAncestors(child.getAncestors().replace(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            areaMapper.updateAreaChildren(children);
        }
    }

    /**
     * 删除区域管理信息
     * 
     * @param
     * @return 结果
     */
    @Override
    public int deleteAreaById(Long areaId)
    {
        return areaMapper.deleteAreaById(areaId);
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysArea> list, SysArea t)
    {
        // 得到子节点列表
        List<SysArea> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysArea tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                // 判断是否有子节点
                Iterator<SysArea> it = childList.iterator();
                while (it.hasNext())
                {
                    SysArea n = (SysArea) it.next();
                    recursionFn(list, n);
                }
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysArea> getChildList(List<SysArea> list, SysArea t)
    {
        List<SysArea> tlist = new ArrayList<SysArea>();
        Iterator<SysArea> it = list.iterator();
        while (it.hasNext())
        {
            SysArea n = (SysArea) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getAreaId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysArea> list, SysArea t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }
}
